<?php

namespace plugin\admin\app\controller;

use app\service\OrderService;
use plugin\admin\app\model\RlMember;
use support\Request;
use support\Response;
use plugin\admin\app\model\RlOrder;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;
use const support\CORRECT;

/**
 * 订单列表 
 */
class RlOrderController extends Crud
{
    
    /**
     * @var RlOrder
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new RlOrder;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('rl-order/index');
    }

    /**
     * 获取
     * @return Response
     */
    public function select(Request $request): Response
    {
        $page = (int)$request->get('page');
        $limit = (int)$request->get('limit', 10);
        $count=RlOrder::where('status',CORRECT)->count();
        $offset=($page-1)*$limit;
        $lists= RlOrder::where('status',CORRECT)->orderBy('id','desc')
            ->offset($offset)->limit($limit)->get()->toArray();
        //获取用户ID
        $memberIds=array_column($lists,'member_id');
        $members=RlMember::whereIn('id',$memberIds)->get()->toArray();
        $members=array_column($members,null,'id');
        //进行昵称头像追加
        foreach ($lists as &$list){
            $list['nickname']=$members[$list['member_id']]['nickname']??'';
            $list['avatar']=$members[$list['member_id']]['avatar']??'';
            $list['mobile']=$members[$list['member_id']]['mobile']??'';
        }
        return json(['code' => 0, 'data' => $lists, 'count'=>$count,'msg' => '成功']);
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('rl-order/update');
    }

    //退款操作
    public function refund(Request $request){
        if ($request->method() === 'POST') {
            //接收
            $orderId=$request->post('id');
            $orderRefundDesc=$request->post('order_refund_desc');
            //查询订单信息
            $memberId=RlOrder::where([
                'id'        =>$orderId,
                'status'    =>CORRECT,
                'order_status'=>CORRECT
            ])->value('member_id');
            if (empty($memberId)){
                return $this->json(-1,'无效订单');
            }
            list($retCode,$msg,$data)=OrderService::toApplyRefund($memberId,$orderId,$orderRefundDesc,true);
            if ($retCode){
                return $this->json($retCode,$msg);
            }
            return json(['code' => 0, 'msg' => '成功']);
        }
        return view('rl-order/refund');
    }

    //详情
    public function details(){

        return view('rl-order/details');
    }

}
